import { create } from "zustand";
import {
  ChatMessage, ChatMessageMediaData, ChatMessageOrTimeLine,
  ChatMessageUpdate, MessageType,
} from "@/types/chat-message";
import {groupMessagesWithTimeLine} from "@/utils/time-utils";

interface ChatMessageState {
  state: {
    loading: boolean; // 是否正在加载消息列表
    messages: ChatMessage<any, any>[];
    groupedMessages: ChatMessageOrTimeLine[]; // 分组消息记录
    imgUrls: ChatMessageMediaData[]; // 可预览媒体文件URL列表
  };
  actions: {
    /**
     * 设置加载状态
     * @param loading 是否正在加载
     */
    setLoading: (loading: boolean) => void;
    /**
     * 获取整个消息列表
     * @param sessionId 会话ID
     */
    setMessages: (messages: ChatMessage<any, any>[]) => void;
    /**
     * 添加一条消息记录
     * @param message 消息内容
     */
    addMessage: (message: ChatMessage<any, any>) => void;
    /**
     * 批量添加消息记录
     * @param messages 消息内容列表
     */
    addBatchMessages: (messages: ChatMessage<any, any>[]) => void;
    /**
     * 更新指定消息
     * @param message 消息内容
     */
    updateMessage: (message: ChatMessageUpdate) => void;
    /**
     * 删除指定的消息记录
     * @param del 消息ID
     */
    deleteMessage: (del: string) => void;
    /**
     * 批量删除指定的消息记录
     * @param del 消息ID列表
     */
    deleteBatchMessages: (del: string[]) => void;
  };
}

const ChatMessageStateStore = create<ChatMessageState>((set, get) => ({
  state: {
    loading: false, // 初始状态为未加载
    messages: [],
    groupedMessages: [], // 分组消息记录
    imgUrls: [], // 可预览媒体文件URL列表
  },
  actions: {
    setLoading(loading: boolean): void {
      set((currentState) => ({
        state: {
          ...currentState.state,
          loading, // 设置加载状态
        },
      }));
    },
    setMessages(messages: ChatMessage<any, any>[]): void {
      const groupedMessages = groupMessagesWithTimeLine(messages)
      const imgUrls = messages
          .filter((msg) => msg.messageType === MessageType.EMOJI || msg.messageType === MessageType.IMAGE)
          .map((msg) => ({ url: msg.content.url as string, type: msg.messageType, messageId: msg.messageId  }));
      set((currentState) => ({
        state: {
          ...currentState.state,
          messages, // 设置消息记录
          groupedMessages,
            imgUrls, // 设置媒体文件URL列表
        },
      }));
    },
    addMessage: (message: ChatMessage<any, any>) => {
      set((currentState) => {
        const updatedMessages = [...currentState.state.messages, message];
        const groupedMessages = groupMessagesWithTimeLine(updatedMessages);
        const imgUrls = updatedMessages
            .filter((msg) => msg.messageType === MessageType.EMOJI || msg.messageType === MessageType.IMAGE)
            .map((msg) => ({ url: msg.content.url as string, type: msg.messageType, messageId: msg.messageId  }));
        return {
          state: {
            ...currentState.state,
            messages: updatedMessages, // 更新消息记录
            groupedMessages, // 更新分组消息记录
            imgUrls
          },
        };
      });
    },
    addBatchMessages: async (messages: ChatMessage<any, any>[]) => {
      const groupedMessages = groupMessagesWithTimeLine(messages);
        const imgUrls = messages
                      .filter((msg) => msg.messageType === MessageType.EMOJI || msg.messageType === MessageType.IMAGE)
            .map((msg) => ({ url: msg.content.url as string, type: msg.messageType , messageId: msg.messageId }));
      set((currentState) => ({
        state: {
          ...currentState.state,
          messages: [...currentState.state.messages, ...messages], // 将新消息批量添加到记录中
            groupedMessages: [...currentState.state.groupedMessages, ...groupedMessages], // 批量添加分组消息记录
            imgUrls: [...currentState.state.imgUrls, ...imgUrls], // 批量添加媒体文件URL列表
        },
      }));
    },
    updateMessage: (message: ChatMessageUpdate) => {
      set((currentState) => ({
        state: {
          ...currentState.state,
          messages: currentState.state.messages.map((msg) =>
              msg.messageId === message.messageId ? { ...msg, ...message } : msg
          ),
          groupedMessages: currentState.state.groupedMessages.map((msg) =>
              msg.type === "message" && msg.data.messageId === message.messageId ? { ...msg, data: { ...msg.data, ...message } } : msg
          ),
        },
      }));
    },
    deleteMessage: (del: string) => {
      set((currentState) => ({
        state: {
          ...currentState.state,
          messages: currentState.state.messages.filter(
            (message) => message.messageId !== del
          ), // 从记录中移除被删除的消息
            groupedMessages: currentState.state.groupedMessages.filter(
                (msg) => msg.type !== "message" || msg.data.messageId !== del
            ), // 从分组消息记录中移除被删除的消息
            imgUrls: currentState.state.imgUrls.filter(
                (media) => media.messageId !== del
            ), // 从媒体文件URL列表中移除被删除的消息
        },
      }));
    },
    deleteBatchMessages: (del: string[]) => {
      set((currentState) => ({
        state: {
          ...currentState.state,
          messages: currentState.state.messages.filter(
            (message) => !del.includes(message.messageId)
          ), // 从记录中移除被删除的消息
            groupedMessages: currentState.state.groupedMessages.filter(
                (msg) => msg.type !== "message" || !del.includes(msg.data.messageId)
            ), // 从分组消息记录中移除被删除的消息
            imgUrls: currentState.state.imgUrls.filter(
                (media) => !del.includes(media.messageId)
            ), // 从媒体文件URL列表中移除被删除的消息
        },
      }));
    },
  },
}));

export default ChatMessageStateStore;
